<template>
    <div class="content">
        <div class="box" v-loading='loading'>
            <div class="appTitle">
                <h3>{{title}}</h3>
            </div>  
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px" class="demo-ruleForm" :label-position="labelPosition">
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="课程标题" prop="lessonName" v-if="rangeIsShow">  
                            <el-popover placement="top-start" trigger="focus" content="字符长度不大于30个字" >
                                <el-input v-model="ruleForm.lessonName" :maxlength="30" placeholder="请输入课程标题"  slot="reference"></el-input>
                            </el-popover>                                                
                            <!-- <div v-else>{{ruleForm.lessonName}}</div> -->
                        </el-form-item>
                        <el-form-item label="课程标题" v-else>{{ruleForm.lessonName}}</el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10" class="upload-image"> 
                        <el-form-item label="课程图片">
                            <file-upload 
                                    @remove="fileImgRemove" 
                                    @onSuccess="onSuccess"
                                    :file-list.sync="imgOptions.fileList" 
                                    :file-list-show.sync="imgOptions.fileListShow"
                                    v-if="rangeIsShow"
                                    :imgSize="8">
                                     <div class="up-container el-upload">
                                        <i class="el-icon-plus"></i>
                                    </div> 
                            </file-upload>
                            <div class="lesson-img-wrapper" v-else>
                                <img :src="ruleForm.lessonImg" :alt="ruleForm.lessonImg == ''?'课程默认图':'课程图片'"  >
                                <!-- <img :src="ruleForm.lessonImg == ''?require('../../../../assets/lessonManage.png'):ruleForm.lessonImg" :alt="ruleForm.lessonImg == ''?'课程默认图':'课程图片'" > -->
                            </div>
                            <!-- <imgUpload v-model="imgOptions.lessonImg" ref="clearFile" :imageSize="8" ></imgUpload> -->
                            <p class="remark" v-if="rangeIsShow">
                                支持gif，jpg，jpeg，png格式，大小不超过8MB；推荐尺寸：750*300；不上传则显示默认图，建议上传。
                            </p>
                        </el-form-item> 
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="开课时间" prop="startDate"  v-if="rangeIsShow"> 
                            <el-date-picker
                                :editable="false"
                                v-model="ruleForm.startDate"
                                type="datetime"
                                placeholder="选择开课时间"
                                :picker-options="ruleForm.pickerOptions1"
                                format="yyyy-MM-dd HH:mm:ss"
                                @change="dateChange1"
                                style="width:100%"
                               >
                            </el-date-picker>
                            <!-- <div v-else>{{ruleForm.startDate}}</div> -->
                        </el-form-item>
                        <el-form-item label="开课时间" v-else>{{ruleForm.startDate}}</el-form-item>
                    </el-col>
                </el-row> 
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="预计结束时间" prop="endDate" v-if="rangeIsShow">
                            <el-date-picker
                                :editable="false"
                                v-model="ruleForm.endDate"
                                type="datetime"
                                placeholder="选择预计结束时间"
                                :picker-options="ruleForm.pickerOptions2"
                                format="yyyy-MM-dd HH:mm:ss"
                                @change="dateChange2"
                                style="width:100%"
                                >
                            </el-date-picker> 
                        </el-form-item>
                        <el-form-item label="预计结束时间" v-else>{{ruleForm.endDate}}</el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="选择摄像头" prop="cameraId" >
                            <el-select v-model="ruleForm.cameraId" placeholder="请选择摄像头"  style="width:100%"  v-if="rangeIsShow">
                                <el-option
                                    v-for="item in cameraList"
                                    :key="item.pId"
                                    :label="item.sAngleView"
                                    :value="item.pId"
                                   >
                                </el-option>
                             </el-select> 
                             <div v-else>{{ruleForm.cameraId}}</div>
                        </el-form-item>
                    </el-col>
                </el-row>     
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="开放范围" required v-if="rangeIsShow">
                            <p>全校</p>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="适合人群" prop="fitPeople" v-if="rangeIsShow">
                            <el-popover placement="top-start" trigger="focus" content="字符长度不大于30个字">
                                <el-input type="textarea" v-model="ruleForm.fitPeople" :maxlength="30"  resize="none" slot="reference"></el-input>
                            </el-popover>    
                            <!-- <div v-else>{{ruleForm.fitPeople}}</div> -->
                        </el-form-item>
                        <el-form-item label="适合人群" v-else>{{ruleForm.fitPeople}}</el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="课程亮点" prop="lightspot" >
                            <el-popover placement="top-start" trigger="focus" content="字符长度不大于1000个字" >
                                <el-input type="textarea" v-model="ruleForm.lightspot" :autosize="{ minRows: 3, maxRows: 6}" :maxlength="1000" placeholder="课程概述与亮点" resize="none" slot="reference"></el-input>
                            </el-popover>  
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="授课老师" prop="teacherName" >
                            <el-popover placement="top-start" trigger="focus" content="字符长度不大于15个字" >
                                <el-input v-model="ruleForm.teacherName" :maxlength="15" placeholder="请输入授课老师的名字" slot="reference"></el-input>
                            </el-popover>  
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10" class="upload-image teacher-img">
                        <el-form-item label="授课老师图片">
                            <file-upload 
                                    @remove="fileImgRemove2" 
                                    @onSuccess="onSuccess2"
                                    :file-list.sync="imgOptions.fileList2" 
                                    :file-list-show.sync="imgOptions.fileListShow2"
                                    :imgSize="1">
                                     <div class="up-container el-upload">
                                        <i class="el-icon-plus"></i>
                                    </div>
                                    <!-- <img v-if="ruleForm.teacherImg" :src="ruleForm.teacherImg" class="avatar"> -->
                                    <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
                            </file-upload>
                            <p class="remark">
                                支持gif，jpg，jpeg，png格式，大小不超过1MB；推荐尺寸：100*100
                            </p>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="授课老师简介" prop="teacherIntroduce" >
                            <el-popover placement="top-start" trigger="focus" content="字符长度不大于300个字" >
                                <el-input type="textarea" v-model="ruleForm.teacherIntroduce" :autosize="{ minRows: 3, maxRows: 6}" :maxlength="300" placeholder="教师简介" resize="none" slot="reference"></el-input>
                            </el-popover> 
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10" class="course-img">
                        <el-form-item label="相关课件" >
                            <file-upload 
                                    :file-list.sync="imgOptions.fileList3" 
                                    :file-list-show.sync="imgOptions.fileListShow3"
                                    :upFileType="imgOptions.upFileType"
                                    @onSuccess="onSuccess3"
                                    @remove="fileImgRemove3"
                                    :fileSize="20">
                                    <!-- <i class="el-icon-plus avatar-uploader-icon"></i> -->
                                      <el-button >上传附件</el-button>
                            </file-upload>
                            <p class="remark">
                                仅支持word、ppt、excel、txt、pdf等格式，课件大小不超过20M
                            </p>  
                        </el-form-item> 
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="分类标签" prop="teacherTag" >
                            <el-popover placement="top-start" trigger="focus" content="最多可添加5个标签，一个标签不可超过8个字" v-if="rangeIsShow">
                                <el-input type="text" v-model="ruleForm.teacherTag" :maxlength="44" placeholder="标签间请用英文逗号隔开，最多可添加5个标签，一个标签不可超过8个字" slot="reference"></el-input>
                            </el-popover> 
                            <div v-else>{{ruleForm.teacherTag}}</div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item class="footer">
                    <el-button @click="resetForm">取消</el-button>
                    <el-button type="primary" @click="submitForm('ruleForm')" :disabled="btnDisabled">发布</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>

</template>

<script>
import moment from 'moment';
import { mapGetters } from 'vuex';
import school from 'components/SchoolClasss/school';
import fileUpload from 'components/Upload/fileUpload';
import imgUpload from 'components/Upload/imgUpload';
import { checkCameraBySchoolId, addNewLesson, getLessonDetailByPid, updateLesson } from 'api/onlineLesson'; 
export default {
    name: 'addNewLessonList',
    components: { school, fileUpload, imgUpload},
    data() {
        // 验证规则
        var validStart = (rule, value, callback) => {
            if (value == '') {
                return callback(new Error('请选择开课时间')); 
            } else {
                let now = new Date();
                let time = now.getTime() - 60000; 
                if (value <= time) {
                    return callback(new Error('开课时间必须大于等于当前时间'));  
                }
                callback();
            }
        };
        var validEnd = (rule, value, callback) => {
            if (value == '') {
                return callback(new Error('请选择预计结束时间')); 
            } else {
                if (value < this.ruleForm.startDate) {
                    return callback(new Error('预计结束时间必须大于开课时间'));  
                }
                callback();   
            }
        };
        var validTags = (rule, value, callback) => {
            if (value !== '') {
                let tagList = value.split(',');
                if (tagList.length > 5) {
                    return callback(new Error('标签个数不可以多于5个！')); 
                } else {
                    for (let i = 0; i < tagList.length; i++) {
                        if (tagList[i].length > 8) {
                            return callback(new Error('一个标签不可超过8个字')); 
                        }
                    }
                    return callback(); 
                }
            }
            callback(); 
        
        };
        return {
            value1: '',
            loading: false,
            labelPosition: 'right', // label左对齐
            title: '发布课程', // 标题
            pid: '', // 课程ID
            rangeIsShow: true, // 开放范围是否显示，默认显示    
            imgOptions: {
                fileList: [], // 课程图片
                fileListShow: true,
                fileList2: [], // 教师头像
                fileListShow2: true,
                upFileType: 'file', // 上传相关课件
                fileList3: [], // 上传相关课件
                fileListShow3: true, // 上传相关课件
                courseUrl: '', // 相关课件的上传的绝对路径
                courseName: '', // 相关课件的文件名
                courseSize: '' // 课件大小
            },
            ruleForm: {
                // schoolName: '', // 学校名称
                // schoolId: '380741938153787392', // 学校ID
                lessonName: '', // 课程标题
                lessonImg: '', // 课程图片
                startDate: '',
                endDate: '',
                cameraId: '',
                fitPeople: '全校师生', // 适合人群
                lightspot: '', // 课程亮点
                teacherName: '', // 授课老师
                teacherImg: '', // 授课老师图片
                teacherIntroduce: '', // 授课老师介绍
                teacherTag: '', // 教师标签
                pickerOptions1: {
                    disabledDate(time) {
                        return time.getTime() < new Date().getTime() - 864e5 ;
                    }
                },
                pickerOptions2: {
                    disabledDate(time) {
                        return time.getTime() < new Date().getTime() - 864e5;
                    }
                }
            },
            rules: {
                schoolName: [
                    {required: true, message: '请输入学校名称', trigger: 'blur' }
                ],
                lessonName: [
                    { required: true, message: '请输入课程标题', trigger: 'blur' },
                    { pattern: /^[^\s]+$/, message: '请输入合法的课程标题', trigger: 'blur' }
                ],
                startDate: [
                    { type: 'date', required: true, message: '请选择开课时间', trigger: 'blur' },
                    { validator: validStart, trigger: 'change'}
                ],
                endDate: [
                    { type: 'date', required: true, message: '请选择预计结束时间', trigger: 'blur' },
                    { validator: validEnd, trigger: 'change'}
                ],
                cameraId: [
                    {required: true, message: '请选择摄像头', trigger: 'blur' }
                ],
                teacherName: [
                     {required: true, message: '请输入教师名称', trigger: 'blur' },
                     { pattern: /^[^\s]+$/, message: '请输入合法的教师名称', trigger: 'blur' }
                ],
                fitPeople: [
                    {required: true, message: '请输入适合人群', trigger: 'blur' },
                    { pattern: /^[^\s]+$/, message: '请输入合法的适合人群', trigger: 'blur' }
                ],
                lightspot: [
                    {required: true, message: '请输入课程概述与亮点', trigger: 'blur' }
                    // { pattern: /^[^\s]+$/, message: '请输入合法的课程概述与亮点', trigger: 'blur' }
                ],
                teacherTag: [
                    { pattern: /^[^\s]+$/, message: '请不要输入空格！', trigger: 'blur' },
                    { validator: validTags, trigger: 'blur' }
                ]
            },
            cameraList: [],
            schoolLoading: false, // 学校的模糊搜索加载
            btnDisabled: false, // 按钮禁用
            isVisibleLessonImg: false // 是否显示课程默认图片

        };
    },
    created() {
        this.pid = this.$route.params.lId; // 获取课程Id
        // 获取课程详情
        this.getLessonDetail();

        // 获取摄像头
        this.getCameraBySchoolId()
    },
    computed: {
        ...mapGetters([
            'schoolId',
            'schoolName'
        ])

    },
    methods: {
        // 根据课程ID查询课程的内容
        getLessonDetail() {
            if (this.pid !== undefined) {
                this.title = '修改课程';
                this.rangeIsShow = false; // 不显示开放范围
                this.loading = true;
                getLessonDetailByPid(this.pid).then(res => {
                    this.loading = false;
                   
                    let lessonObj = res.data.content;
                    if (lessonObj.sPicture == '') this.isVisibleLessonImg = true; // 显示默认图
                    this.ruleForm.schoolName = lessonObj.sSchoolName;
                    this.ruleForm.lessonName = lessonObj.sTitle;
                    this.ruleForm.lessonImg = lessonObj.sPicture == ''?require('../../../../assets/lessonManage.png'):lessonObj.sPicture;
                    this.ruleForm.startDate = lessonObj.sStartTime;
                    this.ruleForm.endDate = lessonObj.sExpectEndTime;
                    this.ruleForm.cameraId = lessonObj.sAngleView;
                    this.ruleForm.fitPeople = lessonObj.sSuitPeople;
                    this.ruleForm.lightspot = lessonObj.sHighlights;
                    this.ruleForm.teacherName = lessonObj.sTeacherName;
                    this.ruleForm.teacherImg = lessonObj.sTeacherPicture;
                    lessonObj.sTeacherPicture == ''? this.imgOptions.fileList2 = [] : this.imgOptions.fileList2.push({name: '', url: lessonObj.sTeacherPicture});       
                    this.ruleForm.teacherIntroduce = lessonObj.sTeacherIntroduction;
                     // 处理上传的文件列表显示
                    lessonObj.sCourseware == ''?this.imgOptions.fileList3=[] : this.imgOptions.fileList3.push({
                        name: lessonObj.sCoursewareName,
                        url: lessonObj.sCourseware
                    });
                    this.imgOptions.courseName = lessonObj.sCoursewareName;
                    this.imgOptions.courseUrl = lessonObj.sCourseware;
                    this.imgOptions.courseSize = lessonObj.sCoursewareSize;
                    this.ruleForm.teacherTag = lessonObj.sTags;
                }).catch(() => {
                    this.loading = false;
                });
            }     
        },

        // 根据学校ID查询是否有可用的摄像头
        getCameraBySchoolId() {
            checkCameraBySchoolId(this.schoolId).then(res => {
                
                let list = res.data.content;
                if (list.length > 0) {
                    this.cameraList = list;
                }
            })
        },
         // 功能：开始日期选择
        dateChange1(date) {
            this.ruleForm.pickerOptions2 = {
                disabledDate(time) {
                    
                    return time.getTime() < new Date(date).getTime() - 864e5 || time.getTime() < new Date().getTime() - 864e5;
                }
            };
        },

    // 功能：结束日期选择
        dateChange2(date) {
            this.ruleForm.pickerOptions1 = {
                disabledDate(time) {
                   
                    return time.getTime() > new Date(date).getTime() || time.getTime() < new Date().getTime() - 864e5;
                }
            };
        },

        // 移除课程图片
        fileImgRemove(data) {
            this.ruleForm.lessonImg = ''; 
        },

        // 移除教师头像
        fileImgRemove2(data) {
            this.ruleForm.teacherImg = ''; 
        },

        // 移除文件
        fileImgRemove3(data) {
            this.imgOptions.fileList3 = [];
            this.imgOptions.courseUrl = '';
            this.imgOptions.courseName = '';
        },

        // 课程图片上传成功
        onSuccess(data) {
            
            this.ruleForm.lessonImg = data.imgUrl;
            this.$message.success('课程图片上传成功'); 
        },

        // 教师头像上传
        onSuccess2(data) {
            
            this.ruleForm.teacherImg = data.imgUrl;
            this.$message.success('教师头像上传成功'); 
        },
        
        // 文件上传成功
        onSuccess3(data) {
           
            this.imgOptions.courseUrl = data.imgUrl;
            this.imgOptions.courseName = data.fileName;
            this.imgOptions.courseSize = this.imgOptions.fileList3.length == 0?'':this.imgOptions.fileList3[0].response.content.fileSize;   
            
            this.$message.success('文件上传成功！'); 
        },

        // 发布课程
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let message = '是否发布课程？';
                    if (this.pid) message = '是否确认修改？';
                    this.$confirm(message, ' ', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消'
                    }).then(() => {   
                        // 禁用按钮
                        this.btnDisabled = true;
                        // 调用接口 
                        if (this.pid) { // 修改   
                            this.update();
                            this.$router.push({ path: '/onlineLesson/list' });
                        } else { // 新增
                            let startTemp = moment(this.ruleForm.startDate).format('YYYY-MM-DD HH:mm:ss');
                            let endTemp = moment(this.ruleForm.endDate).format('YYYY-MM-DD HH:mm:ss');
                            let cameraName = this.cameraList.find(item => {
                                return item.pId == this.ruleForm.cameraId;
                            })
                            this.add(startTemp, endTemp, cameraName.sAngleView);
                            
                        }     
                    }).catch((e) => {  
                        this.btnDisabled = false; // 解禁按钮  
                    }); 
                } else {
                    this.btnDisabled = false; // 解禁按钮
                    return false;
                }
            });
        },

        // 新增课程的接口
        add(startTime, endTime, sAngleView) {
            this.loading = true;
            addNewLesson(
                this.schoolId,
                this.schoolName,
                this.ruleForm.lessonName,
                this.ruleForm.lessonImg,
                startTime,
                endTime,
                this.ruleForm.cameraId,
                sAngleView,
                this.ruleForm.fitPeople,
                this.ruleForm.lightspot,
                this.ruleForm.teacherName,
                this.ruleForm.teacherImg,
                this.ruleForm.teacherIntroduce,
                this.imgOptions.courseUrl,
                this.imgOptions.courseName,
                this.imgOptions.courseSize,
                this.ruleForm.teacherTag
            ).then(res => {
                this.loading = false;
                if (res.data.status == 200) {
                    this.$message({
                        type: 'success',
                        message: '发布成功!'
                    });
                    this.$store.dispatch('UpdateCache');  // 整页刷新
                    this.$router.push({ path: '/onlineLesson' })
                    
                }
            }).catch(() => {
                this.loading = false;
                this.btnDisabled = false;
            })
        },

        // 修改课程的接口
        update() {
            this.loading = true;
            updateLesson(
                this.pid,
                this.ruleForm.lightspot,
                this.ruleForm.teacherName,
                this.ruleForm.teacherImg,
                this.ruleForm.teacherIntroduce,
                this.imgOptions.courseUrl,
                this.imgOptions.courseName,
                this.imgOptions.courseSize,
            ).then(res => {
                this.loading = false;
                if (res.data.status == 200) {
                    this.$message({
                        type: 'success',
                        message: '修改成功!'
                    });
                    this.$store.dispatch('UpdateCache', true);  // 列表刷新 
                }

            }).catch(() => {
                this.btnDisabled = false;
                this.loading = false;
            })
        },
        // 返回上一页
        resetForm() {
            this.$router.go(-1);
        }
    }
};
</script>

<style lang="scss" scoped>
.content {
  padding: 0 50px;
  box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
  -webkit-box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
  background: #fff;
  .box {
        padding-bottom: 20px;
        background: #fff;
    .appTitle {
        padding-top:8px;
        text-align: center;
        font-size: 18px;
        color: #333;
        line-height: 72px;
        font-weight: bold;
        font-family: Microsoft YaHei;
        border-bottom: 1px solid #ddd;
        margin-bottom: 40px;
    }

    .form-date {
      padding: 14px 0 35px 16px;
      font-size: 14px;
      color: #333;
    }

    .upload-image {
        margin-left: 0;
        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }

        .avatar-uploader .el-upload:hover {
            border-color: #20a0ff;
        }
        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
        }
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }
    }

    .lesson-img-wrapper{
        width:750px;
        height:300px;

        img{
            width:100%;
            height:100%;
        }
    }

    .teacher-img{
        .avatar-uploader-icon {
            width: 100px;
            height: 100px;
            line-height: 100px;
        }
        .avatar {
            width: 100px;
            height: 100px;    
        }
    }

    .course-img{
        .avatar-uploader-icon {
            font-size: 14px;
            color: #8c939d;
        }
        // .avatar-uploader-icon:after{
        //     content:' 添加文件';
        // }
    }

    .remark{
        font-size: 14px;
        color: #ccc;
        padding-top: 4px;
        line-height: 20px;
     }   

    .footer {
      text-align: center;
      margin: 80px 0 40px 0;

      .el-button {
        padding: 10px 40px;
      }
    }
  }
}
</style>


